package com.rainner.app.util.dbutil;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.DataSources;

/**
 * 数据连接池工厂
 * 
 * @author jacky
 * 
 */
public class DBPoolFactory {
	public static final String MYSQL = "MYSQL";
	private static DBPoolFactory instance = new DBPoolFactory();
	// 存储多个连接池(支持多种数据库同时存在)
	private static Map<String, DataSource> poolMap = new HashMap<String, DataSource>();

	static {
		instance.add(MYSQL);
		// instance.add(MYSQL, "com.mysql.jdbc.Driver",
		// "jdbc:mysql://127.0.0.1/CREDIT_CHINA", "root", "system");
	}

	private DBPoolFactory() {

	}

	public static DBPoolFactory getInstance() {
		// if (instance == null) {
		// try {
		// instance = new DBPoolFactory();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		return instance;
	}

	// public void add(String key, String configFile) {
	// // read config from file, and build a dbpool
	// }

	/**
	 * 向连接池列表添加一个新的池化（Pooled）数据源
	 * 
	 * @param key
	 * @param driver
	 *            数据连接驱动，如com.mysql.jdbc.Driver
	 * @param url
	 *            连接串， 如jdbc:mysql://localhost/samland
	 * @param username
	 *            数据库连接用户名，如samland
	 * @param password
	 *            数据库连接用户密码
	 * @throws Exception
	 */
	public void add(String key, String driver, String url, String username,
			String password) {
		try {
			if (key == null)
				throw new Exception("key is null");
			Class.forName(driver);
			DataSource ds_unpooled = DataSources.unpooledDataSource(url,
					username, password);
			DataSource ds_pooled = DataSources.pooledDataSource(ds_unpooled);
			if (poolMap.containsKey(key)) {
				poolMap.remove(key);
			}
			poolMap.put(key, ds_pooled);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void add(String key) {
		try {
			if (key == null)
				throw new Exception("key is null");
			// Class.forName(driver);
			DataSource ds_unpooled = DataSources.unpooledDataSource();
			DataSource ds_pooled = DataSources.pooledDataSource(ds_unpooled);
			if (poolMap.containsKey(key)) {
				poolMap.remove(key);
			}
			poolMap.put(key, ds_pooled);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean containsKey(String key) {
		return poolMap.containsKey(key);
	}

	public DataSource getDataSource(String key) {

		return poolMap.get(key);
	}
}
